<template>
  <m-expand-box
    v-clickoutside="handleClickOutSide"
    class="v-graph-sider"
    :minWidth='60'
    :initWidth='initWidth'
    :draglineShow="true"
    contentClass="v-graph-sider-bar"
  >
    <a-collapse  v-model="activeKey" expandIconPosition="right">
      <!-- <template slot="expandIcon">
        <img src="statics/icons/app/arrowd.svg">
      </template> -->
      <template #expandIcon="{ isActive }">
        <div>
          <img src="statics/icons/app/arrowdown12.svg" class="_collapse-icon" :class="{_expand:isActive}">

        </div>

      </template>
      <a-collapse-panel
        v-for="menu in menus"
        :key="menu.value"
        :class="{_expand:activeKey.includes(menu.enName)}">
        <img slot="extra" :src="menu.iconPath" class="g-m-r-5"/>
        <span slot="header" class="_menu-item-text">{{menu.label}}</span>
        <div
          v-for="item in menu.children"
          ref="activePanel"
          :key="item.value"
          class="_menu-item"
          @mousedown="handleSetDragData(item)">
          <img :src="item.iconPath" class="g-m-r-4"/> 
          <span class="_menu-item-text">{{item.label}}</span>
        </div>
      </a-collapse-panel>
    </a-collapse>
    <div v-if="dragData" class="_pointer-icon" :style="pointerIcon" ><!-- 点击拖拽到画布上 -->
      <img :src="dragData.iconPath" class="g-m-r-5"/> {{dragData.label}}
    </div>
  </m-expand-box>
</template>
<script>
import Clickoutside from 'components/common/ContextMenu/clickoutside';
import ExpandBox from 'components/common/ExpandableBox';
import expandIcon from 'statics/icons/app/arrowd.svg';
import { treeForEach } from '@/util/common';
import { chooseElement } from '@/components/common/ChooseElement.vue';
import { graphHelper } from '@/api/GraphHelper';

export default {
  name: 'comp-sider-bar',
  components: {
    'm-expand-box': ExpandBox,
  },
  directives: {
    Clickoutside,
  },
  props: {
    diagramType: {
      type: String,
      default: 'pkg',
    },
    graph: Object,
  },
  data() {
    //// const includeTypes = diagramMap[this.diagramType];
    return {
      //// menus: menus.filter(menu => includeTypes.includes(menu.title)),
      activeKey: [],
      expandIcon,
      dragData: undefined,
      pointerIcon: {
        left: 0,
        top: 0,
      },
    };
  },
  computed: {
    menus(){
      const siderBarConfigItem = app.activeProject && app.activeProject.configManager && app.activeProject.configManager.getSiderBarConfig()[this.diagramType];
      if (!siderBarConfigItem) return [];
      return siderBarConfigItem.map(item => {
       
        const config = app.activeProject.configManager.getTypeNameConfigItem(item.enName);
        console.log('aaa', siderBarConfigItem, config);
        return {
          label: item.cnName,
          value: item.enName,
          iconPath: config && config.icon,
          children: item.children.map(typeName => {
            const typeNameConfigItem = app.activeProject.configManager.getTypeNameConfigItem(typeName);
            if (!typeNameConfigItem) {
              console.error('not found TypeNameConfigItem:' + typeName);
              return;
            }
            return {
              label: typeNameConfigItem.cnName,
              typeName: typeName,
              iconPath: typeNameConfigItem.icon
            };
          }).filter(Boolean)
        };
      });
    },
    initWidth(){
      return window.screen.width > 1440 ? 200 : 148;
    }
  },
  mounted() {
    this.activeKey = this.diagramType; //// 创建时自动展开工具栏
  },
  beforeDestroy() {
    window.removeEventListener('mousemove', this.handleMouseMove);
    window.removeEventListener('keyup', this.handleKeyUp);
  },
  methods: {
    handleSetDragData(item) {
      if (item.typeName === 'Metaclass'){
        this.clearDragData();
        let metaclasses = [];
        if (graphHelper.getAllMetaclass){
          metaclasses = graphHelper.getAllMetaclass(app.activeProjectId);
        } else {
          treeForEach(app.sysmlModel.children, node => {
            if (node.getTypeName() === 'Metaclass'){
              metaclasses.push(node);
            }
          });
        }
        const children = metaclasses.map(it => ({ label: it.title, typeName: 'Metaclass', icon: item.iconPath, graphNode: it }));
        this.clearDragData();
        chooseElement.popup({
          title: "选择元类型",
          x: window.event.clientX,
          y: window.event.clientY,
          list: [{
            label: '元类型',
            value: 'metaclass',
            children: children
          }]
        }).then(res => {
          res.iconPath = res.icon;
          this.dragData = res;
          console.log(res);
          window.addEventListener('mousemove', this.handleMouseMove);
          window.addEventListener('keyup', this.handleKeyUp);
          this.pointerIcon.left = window.event.clientX + 'px';
          this.pointerIcon.top = window.event.clientY + 'px';
        }).catch(e => e && console.error(e));
      } else {
        //// debugger;
        if (item.typeName === 'Action'){
          
          item = { ...item };
          item.typeName = 'CallBehaviorAction';

        }
        this.dragData = item;
        window.addEventListener('mousemove', this.handleMouseMove);
        window.addEventListener('keyup', this.handleKeyUp);
        this.pointerIcon.left = window.event.clientX + 'px';
        this.pointerIcon.top = window.event.clientY + 'px';

      }

    },
    setTypeNameInDrag(typeName){
      let targetItem;
      for (let i = 0; i < this.menus.length; i++){
        const result = this.menus[i].children.find(item => item.typeName === typeName);
        if (result){
          targetItem = result;
          break;
        }

      }
      if (!targetItem) return;

      this.handleSetDragData(targetItem);

      //// this.menus.find(i=>)
      //// const item = findNodeByValue( this.menus,typeName)
      //// if(item){
      ////   handleSetDragData
      //// }
      //// this.menus

    },
    handleClickOutSide() {
      //// console.log('handleClickOutSide');
      this.clearDragData();
      //// setTimeout(() => {
      ////   this.clearDragData();
      //// }, 100);
    },
    handleMouseMove(event) {
      window.requestAnimationFrame(() => {
        if (this) { ////  可能组件已经销毁
          this.pointerIcon.left = event.clientX + 20 + 'px';
          this.pointerIcon.top = event.clientY + 'px';
        }
      });
    },
    clearDragData() {
      if (this.dragData) {
        window.removeEventListener('mousemove', this.handleMouseMove);
        window.removeEventListener('keyup', this.handleKeyUp);

        this.dragData = undefined;
      }
    },
    handleKeyUp(event) {
      if (event.keyCode === 27) {
        this.clearDragData();

        //// this.handleClickOutSide();
        this.graph.highlight.hide();
      }
    },
  },
};
</script>
<style lang="scss">
.v-graph-sider {
  ._drag-line {
		width: 2px;
		right: -1px;
	}
}

.v-graph-sider-bar {
	width: 148px;
  background: #E1F4FF;
	border-right: 1px solid rgb(177, 206, 226);
	overflow: auto;
	height: calc(100vh - 155px);
	&::-webkit-scrollbar {
		display: none; /* Chrome Safari */
	}
	.ant-collapse {
		border: none;
    ._collapse-icon {
      display: inline-block;
      position: relative;
      transform: scale(0.83333333);
      &._expand {
        transform: rotate(180deg) scale(0.83333333);
      }
    }
    .ant-collapse-extra {
      position: absolute;
      top: 0;
      left: 19px;
      line-height: 24px;
      vertical-align: middle;
      font-size: 0;
    }
		.ant-collapse-item {
			border-bottom: none;
      ._menu-item-text {
        line-height: 24px;
      }
			& > .ant-collapse-header {
        overflow: hidden;
        text-overflow: ellipsis;
				padding: 0 0 0 39px !important;
				font-size: 12px;
				color: rgba(0, 0, 0, 0.65);
				background: #d6ecf9;
				border: 1px solid #b1cee2;
				white-space: nowrap;
				height: 24px;
				&:hover {
					color: rgba(0, 0, 0, 0.85);
					background: linear-gradient(107deg, #a3dbff 0%, #74c5f8 100%);
				}
			}
			&.ant-collapse-item-active {
				& > .ant-collapse-header {
					color: rgba(0, 0, 0, 0.85);
					background: linear-gradient(107deg, #a3dbff 0%, #74c5f8 100%);
				}
			}
			&:last-child {
				border-radius: 0 0 0 0;
				& > .ant-collapse-header {
					border-radius: 0 0 0 0;
				}
			}
		}
	}
	.ant-collapse-content {
    border-radius: 0 !important;
		border-top: none;
    background-color: #e1f4ff;
	}

	.ant-collapse-content > .ant-collapse-content-box {
    padding: 4px;
    border-bottom: 1px solid #B1CEE2;
		._menu-item {
			padding: 1px 1px 1px 17px;
			font-size: 12px;
			line-height: 24px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      > img {
        line-height: 16px;
      }
      > span {
        line-height: 14px;
        vertical-align: middle;
      }
		}
	}
	._pointer-icon {
		position: fixed;
		z-index: 1;
		opacity: 0.65;
	}
}
</style>
